<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网络超时与异常</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: 1px solid #90b;
        }
    </style>
</head>
<body>
    <button>点击获取数据</button>
    <div id="result">

    </div>
    <script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.querySelector('#result');
        btn.onclick = function(){
            const xhr = new XMLHttpRequest();
            //xhr.timeout网络超时
            xhr.timeout = 2000;
            xhr.ontimeout = function(){
                alert('网络超时，请稍后重试');
            }
            //网络异常
            xhr.onerror = function(){
                alert('网络异常，请检查网络');
            }
            xhr.open('GET', 'http://localhost:8000/delay?'+Date.now());
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status < 300){
                        result.innerHTML = xhr.response;
                    }
                }
            }
        }
    </script>
</body>
</html>